/*********************************************
 *GPIO Operation for ESP8266.
 *Author: openthings@163.com. 
 *copyright&GPL V2.
 *Last modified 2014-10-20.
 **********************************************/

#include "c_types.h"
#include "user_interface.h"
#include "xc_version.h"
#include "version.h"
#include "espconn.h"
#include "mem.h"
#include "xc.h"
//#include "xc_ipCmd.h"
#include "osapi.h"
#include "gpio.h"
#include "driver/uart.h"

#include "xc_cmd.h"

extern cmd_functionType cmd_fun[xc_cmdNum];

/*********************************************
 *GPIO=pin,on/off，写GPIO端口，自动设为OUTPUT.
 *********************************************/
void xc_cmd_CGPIO(uint8_t id, char* pParam)
{
	char temp[32];
	uint32 pin;
	
	char delims[] = ",";
	char *iPin = strtok( pParam, delims );
	char *iSwitch =  strtok( NULL, delims );

	if ((iPin==NULL)||(iSwitch==NULL)){
		sendInfoAll("invalid pin or status.");
		return ;
	}

	pin = atoi(iPin);
	os_sprintf(temp, "%s:%d,%s\r", cmd_fun[id].cmdName, pin, iSwitch);
	sendInfoAll(temp);
	
	if ((pin<0)||(pin>13)) {
		sendInfoAll("Invalid GPIO pin.\r");
		return;		
	}

	if (strcmp(iSwitch,"ON")) {		//SET GPIO to ON.
		GPIO_OUTPUT_SET(GPIO_ID_PIN(pin), 1);
	} else if (strcmp(iSwitch,"OFF")) {	//SET GPIO to OFF.
		GPIO_OUTPUT_SET(GPIO_ID_PIN(pin), 0);
	} else {
		sendInfoAll("GPIO must ON or OFF.\r");	
	}
}

/*********************************************
 *GPIOW=pin,on/off，读GPIO端口，自动设为INPUT.
 *********************************************/
void xc_cmd_CGPIOQ(uint8_t id, char* pParam)
{
	uint32 pin,value;
	char temp[32];
	if (pParam==NULL){
		sendInfoAll("Invalid GPIO pin.\r");
		return;
	}
	
	pin = atoi(pParam);
	if ((pin<0)||(pin>13)) {
		sendInfoAll("Invalid GPIO pin.\r");
		return;		
	}

	//sendInfoAll("Unavailable.");
	//Read pin.
	GPIO_DIS_OUTPUT(pin);
	value = GPIO_INPUT_GET(pin);
	os_sprintf(temp, "%s:%02d,%d\r", cmd_fun[id].cmdName, pin, value);
	sendInfoAll(temp);
}